using System.Collections.Specialized;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using NUnit.Framework;
using Salient.SqlServer.Management;

namespace Salient.SqlServer.Tests
{
    [TestFixture]
    public class DatabaseFixture
    {
        private static string ConnectionString
        {
            get { return ConfigurationManager.ConnectionStrings["testdb"].ConnectionString; }
        }
        private static string Server
        {
            get { return new SqlConnectionStringBuilder(ConnectionString).DataSource; }
        }
        private static string Database
        {
            get { return new SqlConnectionStringBuilder(ConnectionString).InitialCatalog; }
        }

        [Test]
        public void CreateNorthwind()
        {
            var db = new Database(ConnectionString);
            var query = new StringCollection() {File.ReadAllText(Path.Combine("scripts","NorthwindExemplar.sql"))};
            db.DropAndCreate(query);
            using (var conn = new SqlConnection(ConnectionString))
            {
                var cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT COUNT(*) FROM CATEGORIES";
                conn.Open();
                var count = cmd.ExecuteScalar();
                Assert.AreEqual(8, count);
                conn.Close();
            }
            db.Drop();
        }
        [Test]
        public void ConnectionStringCtor()
        {
            var db = new Database(ConnectionString);
            db.DropAndCreate();
            db.Drop();
        }
        [Test]
        public void DropAndCreate()
        {
            var db = new Database(Server, Database);
            db.DropAndCreate();
            db.Drop();
        }

        [Test]
        public void Drop()
        {
            var db = new Database(Server, Database);
            db.Drop();
        }

        [Test]
        public void CreateCreateShouldThrow()
        {
            var db = new Database(Server, Database);
            db.DropAndCreate();
            var x = Assert.Throws<SqlException>(db.Create);
            db.Drop();
        }
    }
}